﻿/// <reference path="../../lib/underscore.js" />
/// <reference group="Dedicated Worker" />
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="../Structures/classes.js" />
/// <reference path="../Structures/FolioFixer_DataTypes.js" />

importScripts("../../lib/underscore.js", "//Microsoft.WinJS.1.0/js/base.js", "../Structures/FolioFixer_DataTypes.js")

function getUri(symbol, startDate, endDate) {
    var uri = "http://ichart.finance.yahoo.com/table.csv";
    uri += "?s=" + symbol;

    if (startDate) {
        uri += "&a=" + startDate.getUTCMonth();
        uri += "&b=" + startDate.getUTCDate();
        uri += "&c=" + startDate.getUTCFullYear();
    }

    if (endDate) {
        uri += "&d=" + endDate.getUTCMonth();
        uri += "&e=" + endDate.getUTCDate();
        uri += "&f=" + endDate.getUTCFullYear();
    }

    uri += "&g=d";

    return uri;
}

function requestStockPriceHistory(symbol, startDate, endDate) {
    return new WinJS.Promise(
        function (complete, error) {
            var uri = getUri(symbol, startDate, endDate);

            var request = new XMLHttpRequest();
            WinJS.xhr({ type: "GET", url: uri }).done(
                function (request) {
                    var lines = request.responseText.split('\n');

                    var myStocks = [];

                    for (var i = lines.length - 1; i > 0; i--) {
                        var values = lines[i].split(',');

                        if (values.length == 7) {
                            var stock = new FolioFixer.DataTypes.AssetPriceItem(values, symbol);
                            myStocks.push(stock);
                        }
                    }

                    myStocks = _.sortBy(myStocks, function (stock) { return stock.date; });

                    complete(myStocks);
                }
            );

        }
    );
}

onmessage = function (event) {
    var data = event.data;

    if (data.type == "price_history") {
        requestStockPriceHistory(data.symbol, data.startDate, data.endDate).done(
            function (stocks) {
                postMessage({
                    type: "price_history",
                    symbol: data.symbol,
                    startDate: data.startDate,
                    endDate: data.endDate,
                    stocks: stocks
                });
            });
    }
}
